package cn.b.sky.form.controller;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.form.model.BusinessField;
import cn.b.sky.form.model.Screen;
import cn.b.sky.form.model.ScreenField;
import cn.b.sky.form.model.Section;
import cn.b.sky.form.model.condition.BusinessFieldCondition;
import cn.b.sky.form.model.condition.ScreenCondition;
import cn.b.sky.form.service.BusinessFieldService;
import cn.b.sky.form.service.BusinessTypeService;
import cn.b.sky.form.service.ScreenService;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 
 * <strong>Title : ScreenController.java<br></strong>
 * <strong>Package : cn.b.sky.form.controller<br></strong>
 * <strong>Description : </strong>界面控制器<br> 
 * <strong>Create on : 2016-11-9 上午11:19:43<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/screen/*")
public class ScreenController extends SecurityController {

  @Resource
  ScreenService screenService;

  @Resource
  BusinessTypeService businessTypeService;

  @Resource
  BusinessFieldService businessFieldService;

  @RequestMapping("screenList")
  public String screenList(Model model, @ModelAttribute("condition") ScreenCondition condition, String navTabId) {
    condition.setSiteCode(getSiteCode());
    List<Screen> list = screenService.selectScreenListByCondition(condition);
    int count = screenService.selectScreenListCountByCondition(condition);
    condition.setData(list);
    condition.setTotalCount(count);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "screen/screen_list";
  }

  @RequestMapping("addScreen")
  public String addScreen(String navTabId, Model model) {
    model.addAttribute("businessTypes", businessTypeService.selectBusinessTypes());
    model.addAttribute(NAVTABID, navTabId);
    return "screen/screen_add";
  }

  @RequestMapping("getOnBusinessField")
  public String getOnBusinessField(String[] businessfields, String businessType, Model model) {
    BusinessFieldCondition condition = new BusinessFieldCondition();
    condition.setSiteCode(this.getSiteCode());
    condition.setBusinessType(businessType);
    condition.setBusinessfields(businessfields);
    condition.setOrderField("CreateDateTime");
    condition.setSystemFieldFlag(0);
    List<BusinessField> list = businessFieldService.getOnBusinessField(condition);
    int count = businessFieldService.getOnBusinessFieldCount(condition);
    condition.setData(list);
    condition.setTotalCount(count);
    model.addAttribute("page", condition);
    return "screen/onBusinessField_select";
  }

  @RequestMapping("modifyScreen")
  public String modifyScreen(String navTabId, Model model, String code) {
    model.addAttribute("businessTypes", businessTypeService.selectBusinessTypes());
    model.addAttribute("screen", screenService.getScreen(this.getSiteCode(), code));
    model.addAttribute("pattern", "modify");
    model.addAttribute(NAVTABID, navTabId);
    return "screen/screen_edit";
  }
  
  @RequestMapping("viewScreen")
  public String viewScreen(String navTabId, Model model, String code) {
    model.addAttribute("businessTypes", businessTypeService.selectBusinessTypes());
    model.addAttribute("screen", screenService.getScreen(this.getSiteCode(), code));
    model.addAttribute("pattern", "modify");
    model.addAttribute(NAVTABID, navTabId);
    return "screen/screen_view";
  }
  
  @RequestMapping("saveAs")
  public String saveAs(String navTabId, Model model, String code) {
    model.addAttribute("oldScreenCode", code);
    model.addAttribute(NAVTABID, navTabId);
    return "screen/screen_saveAs";
  }
  
  @RequestMapping("saveAsSection")
  @ResponseBody
  public DWZResult saveAsSection(String navTabId, Model model, String oldScreenCode, Screen screen) {
    setCreateInfo(screen);
    screenService.saveAsSection(this.getSiteCode(),oldScreenCode,screen);
    return dialogAjaxDone(navTabId, null, null, null);
  }
  
  @RequestMapping("getSection")
  @ResponseBody
  public DWZResult getSection(String code,String businessType) {
    if (StringUtils.isBlank(code)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    return ajaxDone(screenService.selectSectionByScreen(this.getSiteCode(),businessType, code));
  }

  @RequestMapping("validateScreen")
  @ResponseBody
  public boolean validateScreen(String screenCode) {
    if (StringUtils.isBlank(screenCode)) {
      return true;
    } else {
      Screen screen = screenService.validateScreen(this.getSiteCode(), screenCode.toUpperCase());
      return screen == null;
    }
  }

  @RequestMapping("saveScreen")
  @ResponseBody
  public DWZResult saveScreen(String sectionMap, Screen screen,String pattern, String navTabId, Model model) {
    if (null == screen) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    setCreateInfo(screen);
    screen.setSiteCode(this.getSiteCode());
    JSONObject object = JSONObject.parseObject(sectionMap);
    List<Section> sectionList = new ArrayList<>();
    @SuppressWarnings("unchecked")
    List<Map<String, Object>> sections = (List<Map<String, Object>>) object.get("elements");
    for (Map<String, Object> map : sections) {
      @SuppressWarnings("unchecked")
      Map<String, Object> section = (Map<String, Object>) map.get("value");
      Section s = new Section();
      s.setSectionOrdinal((Integer) section.get("sectionOrdinal"));
      s.setSectionCode((String) section.get("sectionCode"));
      s.setSectionText((String) section.get("sectionText")); 
      List<ScreenField> screenFieldlList = new ArrayList<>();
      JSONObject object2 = (JSONObject) section.get("screenFields");
      @SuppressWarnings("unchecked")
      List<Map<String, Object>> screenFields = (List<Map<String, Object>>) object2.get("elements");
      for (Map<String, Object> screenFieldmap : screenFields) {
        @SuppressWarnings("unchecked")
        Map<String, Object> screenField = (Map<String, Object>) screenFieldmap.get("value");
        ScreenField sField = new ScreenField();
        sField.setId((Integer) screenField.get("id"));
        sField.setBusinessField((String) screenField.get("businessField"));
        sField.setReadonlyFlag((Integer) screenField.get("readonlyFlag"));
        sField.setFieldOrdinal((Integer) screenField.get("fieldOrdinal"));
        screenFieldlList.add(sField);
      }
      s.setScreenField(screenFieldlList);    
      sectionList.add(s);
    }    
    screen.setSections(sectionList);
    if (!StringUtils.isBlank(pattern)) {
      screenService.updateScreen(screen);
    }else {
      screenService.insertScreen(screen);
    }    
    return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), navTabId, null, null, null);
  }

  @RequestMapping("deleteScreen")
  @ResponseBody
  public DWZResult deleteScreen(String navTabId, Model model, String codes, HttpServletRequest request) {
    String[] idArr = codes.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>();
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      String code = idArr[i];
      String message = null;
      message = screenService.deleteScreen(this.getSiteCode(), code);
      boolean flag = true;
      if (!StringUtils.isBlank(message)) {
        failures += 1;
        flag = false;
        message = getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), message);
      }
      BatchJobReport report = new BatchJobReport(idArr[i], message, flag);
      reports.add(report);
    }
    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(this.getCurrentLanguage(), "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  @RequestMapping("screenLookUp")
  public String screenLookUp(Model model,
                             @ModelAttribute("condition") ScreenCondition condition, String navTabId) {
    condition.setSiteCode(getSiteCode());
    List<Screen> list = screenService.selectScreenListByCondition(condition);
    int count = screenService.selectScreenListCountByCondition(condition);
    condition.setData(list);
    condition.setTotalCount(count);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "screen/screen_lookup";
  }
  
  @RequestMapping("screenSuggest")
  public List<Screen> screenSuggest (@ModelAttribute("condition") ScreenCondition condition){
    condition.setSiteCode(this.getSiteCode());
    return screenService.selectScreenSuggestByCondition(condition);
  }
}
